<?php
error_reporting( 0 );
/**
 * php7 http_server.php
 * 测试
 *   curl http://127.0.0.1:8811/live/index.html
 *   可以打开浏览器，访问 http://127.0.0.1:8811/live/index.html 查看程序的结果。
 *   也可以使用apache ab工具对服务器进行压力测试
 */
$http = new swoole_http_server( '0.0.0.0', 8811 );

// 静态资源返回 http://127.0.0.1:8811/live/index.html
$http->set([
    'enable_static_handler' => true,
    'document_root' => '/Users/abo_o/Dev/workplace/php/swoole2_practice/thinkphp/public/static',
]);

$http->on( 'WorkerStart', function( $http, $worker_ids ) {
    // 定义应用目录
    define('APP_PATH', __DIR__ . '/../application/');

    // 加载基础文件 ~ 不加thinkphp/start.php 的话就不只base.php 还开始执行程序了
    require __DIR__ . '/../thinkphp/base.php';
} );

// 动态资源
$http->on('request', function ($request, $response) use( $http ) {
    list( $_SERVER, $_GET, $_POST ) = serverParamTransport( $request );

    // cookie ...
    // 参数传递: http://127.0.0.1:8811/index/index/index?a=10086&mmm=56
    // 找到对应的控制器: http://127.0.0.1:8811/?s=index/index/hello&name=abo

    info( '请求内容:' . var_export( $request->get, true ) . "\r\n" );
    // 执行应用并响应
    ob_start(); // 页面内容输出,不然会到控制面板
    try {
        think\Container::get('app', [ APP_PATH ] )
            ->run()
            ->send();
    } catch ( \Exception $e ) {
        // todo 自己的业务
    }
    $ret2return = ob_get_contents();
    ob_end_clean();
    info( '返回内容:' . var_export( $ret2return, true ) . "\r\n" );

    $response->header( 'Content-type', 'text/html; charset=utf-8' );
    $response->end( $ret2return );
    // $http->close(); // 找到对应控制器:注销掉上次请求的冗余,重新加载
});

$http->start();

// 基础类库 topthink/think-swoole 初学不建议,因为可以自己封装
function serverParamTransport( swoole_http_request $request )
{

    $_SERVER = $_GET = $_POST = [];
    if ( $request->server ) {
        foreach ( $request->server as $k2server => $v2server ) {
            $_SERVER[ strtoupper( $k2server ) ] = $v2server;
        }
    }

    if ( isset( $request->header ) ) {
        foreach ( $request->header as $k2header => $v2header ) {
            $_SERVER[ strtoupper( $k2header ) ] = $v2header;
        }
    }

    if ( isset( $request->get ) ) {
        foreach ( $request->get as $k2get => $v2get ) {
            $_GET[ $k2get ] = $v2get;
        }
    }

    if ( isset( $request->post ) ) {
        foreach ( $request->post as $k2post => $v2post ) {
            $_POST[ $k2post ] = $v2post;
        }
    }

    // cookie ...

    return [ $_SERVER, $_GET, $_POST ];
}

function info( $msg = '' )
{
    if ( !$msg ) {
        return false;
    }

    return file_put_contents(
        __DIR__ . '/logs/' . date( 'm-d' ) . 'swoole.log',
        $msg . PHP_EOL,
        FILE_APPEND
    );
}